<template>
  <div class="work-time-editor">
    <el-form-item label="">
      <div class="time-periods-container">
        <!-- 时间段列表 -->
        <div
            v-for="(period, index) in timePeriods"
            :key="index"
            class="time-period-item"
        >
          <el-input
              v-model="period.start"
              placeholder="开始时间"
              size="small"
              @blur="validateTimeFormat(period, 'start')"
          >
            <template #suffix>
              <span class="time-separator">-</span>
            </template>
          </el-input>

          <el-input
              v-model="period.end"
              placeholder="结束时间"
              size="small"
              @blur="validateTimeFormat(period, 'end')"
          />

          <el-button
              type="danger"
              size="small"
              @click="removePeriod(index)"
              class="delete-btn"
          >移除该时间段
            <i class="el-icon-delete"></i>
          </el-button>
        </div>

        <!-- 添加按钮 -->
        <el-button
            type="primary"
            size="small"
            @click="addPeriod"
            class="add-btn"
        >
          <i class="el-icon-plus"></i> 添加时间段
        </el-button>
      </div>

      <!-- 原始JSON显示 -->
      <!--<div class="json-preview">-->
      <!--  <el-input-->
      <!--      v-model="workTimeJson"-->
      <!--      placeholder="JSON格式的时间段"-->
      <!--      size="small"-->
      <!--      readonly-->
      <!--  />-->
      <!--</div>-->
    </el-form-item>
  </div>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits, onMounted } from 'vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: '[]'
  }
});

const emits = defineEmits(['update:modelValue']);

// 工具函数：解析JSON格式的工作时间段（先定义后使用）
const parseWorkTimeJson = (jsonStr) => {
  if (!jsonStr) return [{ start: '09:00:00', end: '18:00:00' }];

  try {
    const times = JSON.parse(jsonStr);

    if (Array.isArray(times) && times.length > 0) {
      return times;
    }

    return [{ start: '09:00:00', end: '18:00:00' }];
  } catch (error) {
    return [{ start: '09:00:00', end: '18:00:00' }];
  }
};

// 解析JSON格式的时间段（现在可以正确引用parseWorkTimeJson）
const timePeriods = ref(parseWorkTimeJson(props.modelValue));

// 验证时间格式
const validateTimeFormat = (period, field) => {
  // 正则表达式验证HH:MM:SS格式
  const timeRegex = /^\d{2}:\d{2}:\d{2}$/;

  if (!timeRegex.test(period[field])) {
    period[field] = '00:00:00';
    // 这里可以添加错误提示
  }
};

// 添加新时间段
const addPeriod = () => {
  timePeriods.value.push({
    start: '09:00:00',
    end: '18:00:00'
  });
};

// 移除时间段
const removePeriod = (index) => {
  if (timePeriods.value.length > 1) {
    timePeriods.value.splice(index, 1);
  } else {
    // 至少保留一个时间段
    timePeriods.value[0] = {
      start: '09:00:00',
      end: '18:00:00'
    };
  }
};

// 计算属性：生成JSON字符串
const workTimeJson = computed(() => {
  try {
    return JSON.stringify(timePeriods.value);
  } catch (error) {
    return '[]';
  }
});

// 初始化时同步默认值到父组件
onMounted(() => {
  if (!props.modelValue) {
    emits('update:modelValue', workTimeJson.value);
  }
});

// 监听时间段变化，更新父组件
watch(timePeriods, (newValue) => {
  emits('update:modelValue', workTimeJson.value);
}, { deep: true });

// 监听父组件传入的modelValue变化，更新本地数据
watch(() => props.modelValue, (newValue) => {
  timePeriods.value = parseWorkTimeJson(newValue);
});
</script>

<style scoped lang="scss">
/* 样式保持不变 */
.work-time-editor {
  .time-periods-container {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .time-period-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .time-separator {
        padding: 0 5px;
        color: #999;
      }
    }

    .add-btn {
      width: fit-content;
      margin-top: 8px;
    }
  }

  .json-preview {
    margin-top: 10px;
    font-size: 12px;
    color: #666;

    .el-input {
      cursor: not-allowed;
    }
  }
}
</style>